package com.robot.merchant.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.robot.merchant.client.OrdersClient;
import com.robot.merchant.pojo.MerchantMember;
import com.robot.merchant.pojo.Store;
import com.robot.merchant.pojo.vo.Index;
import com.robot.merchant.service.MerchantMemberService;
import com.robot.merchant.service.StoreService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * 商家数据汇总
 *
 * @author lin
 */
@RestController
@CrossOrigin
@RequestMapping("/index")
public class IndexController {
    @Autowired
    private StoreService storeService;
    @Autowired
    private MerchantMemberService merchantMemberService;

    @Autowired
    private OrdersClient ordersClient;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private HttpServletRequest request;

    /**
     * store表status 0-禁用 1-启用
     */
    private final String storeStatusEnable = "1";
    int page = 1;
    int size = 10;

    /**
     * 首页会员数
     *
     * @return
     */
    @GetMapping(value = "member")
    public Result stores() {
        Claims claims = (Claims) request.getAttribute("robot_merchant");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("storeId=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对商家是否存在和状态进行判断

        Page<MerchantMember> yesterday = merchantMemberService.findMerchantMembersByStoreIdOrderByRegisteredAtDescYesterday(claims.getId(), page, size);
        Page<MerchantMember> week = merchantMemberService.findMerchantMembersByStoreIdOrderByRegisteredAtDescWeek(claims.getId(), page, size);
        Page<MerchantMember> total = merchantMemberService.findMerchantMembersByStoreIdOrderByRegisteredAtDescTotal(claims.getId(), page, size);
        Index index = new Index();
        index.setYesterday(yesterday.getTotalElements() + "");
        index.setWeek(week.getTotalElements() + "");
        index.setTotal(total.getTotalElements() + "");

        HashMap<String, Object> map = new HashMap<>(1);
        map.put("members", index);
        return new Result(StatusCode.SUCCESS_QUERY, map);
    }

    /**
     * 首页订单数
     *
     * @return
     */
    @GetMapping(value = "orders")
    public Result orders() {
        Claims claims = (Claims) request.getAttribute("robot_merchant");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("storeId=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对商家是否存在和状态进行判断

        Index indexOrders = new Index();
        JSONObject yesterday = JSON.parseObject(ordersClient.thirdFindSubOrdersCountByStoreIdAndYesterday(claims.getId(), page, size));
        logger.info("yesterday subOrders=" + yesterday);
        JSONObject week = JSON.parseObject(ordersClient.thirdFindSubOrdersCountByStoreIdAndWeek(claims.getId(), page, size));
        logger.info("week subOrders=" + week);
        JSONObject total = JSON.parseObject(ordersClient.thirdFindSubOrdersCountByStoreIdAndTotal(claims.getId(), page, size));
        logger.info("total subOrders=" + total);
        //为空时置零
        if (yesterday == null) {
            logger.info("merchantModule`s index call ordersModule failed");
            indexOrders.setYesterday("0");
        } else {
            indexOrders.setYesterday(yesterday.get("total").toString());
        }
        if (week == null) {
            logger.info("merchantModule`s index call ordersModule failed");
            indexOrders.setWeek("0");
        } else {
            indexOrders.setWeek(week.get("total").toString());
        }
        if (total == null) {
            logger.info("merchantModule`s index call ordersModule failed");
            indexOrders.setTotal("0");
        } else {
            indexOrders.setTotal(total.get("total").toString());
        }
        HashMap<String, Object> map = new HashMap<>(1);
        map.put("orders", indexOrders);
        return new Result(StatusCode.SUCCESS_QUERY, map);
    }

    /**
     * 首页收益
     *
     * @return
     */
    @GetMapping(value = "revenue")
    public Result revenue() {
        Claims claims = (Claims) request.getAttribute("robot_merchant");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("storeId=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对商家是否存在和状态进行判断

        Index indexRevenue = new Index();
        JSONObject yesterday = JSON.parseObject(ordersClient.thirdFindSubOrdersCountByStoreIdAndYesterday(claims.getId(), page, size));
        logger.info("yesterday subOrders=" + yesterday);
        JSONObject week = JSON.parseObject(ordersClient.thirdFindSubOrdersCountByStoreIdAndWeek(claims.getId(), page, size));
        logger.info("week subOrders=" + week);
        JSONObject total = JSON.parseObject(ordersClient.thirdFindSubOrdersCountByStoreIdAndTotal(claims.getId(), page, size));
        logger.info("total subOrders=" + total);
        //为空时置零
        if (yesterday == null) {
            logger.info("merchantModule`s index call ordersModule failed");
            indexRevenue.setYesterday("0");
        } else {
            indexRevenue.setYesterday(yesterday.get("payAmount").toString());
        }
        if (week == null) {
            logger.info("merchantModule`s index call ordersModule failed");
            indexRevenue.setWeek("0");
        } else {
            indexRevenue.setWeek(week.get("payAmount").toString());
        }
        if (total == null) {
            logger.info("merchantModule`s index call ordersModule failed");
            indexRevenue.setTotal("0");
        } else {
            indexRevenue.setTotal(total.get("payAmount").toString());
        }

        HashMap<String, Object> map = new HashMap<>(1);
        map.put("revenue", indexRevenue);
        return new Result(StatusCode.SUCCESS_QUERY, map);
    }
}
